package com.homedo.odin.solution.service.bizservice.personal;

import static java.util.Comparator.comparingLong;
import static java.util.stream.Collectors.collectingAndThen;
import static java.util.stream.Collectors.toCollection;

import com.homedo.core.common.base.dto.ExcelData;
import com.homedo.core.common.base.dto.Meta;
import com.homedo.core.common.exception.BizException;
import com.homedo.core.common.util.BeanUtils;
import com.homedo.core.common.util.ExportExcelUtils;
import com.homedo.core.common.util.JsonUtils;
import com.homedo.odin.solution.contract.pc.ExportExcelReq;
import com.homedo.odin.solution.contract.pc.ExportExcelResp;
import com.homedo.odin.solution.contract.pc.RelatedSolutionResponseBean;
import com.homedo.odin.solution.dao.SolutionMapper;
import com.homedo.odin.solution.model.dto.SolProductDetailBean;
import com.homedo.odin.solution.model.dto.Tree;
import com.homedo.odin.solution.model.entity.SolProductList;
import com.homedo.odin.solution.model.entity.SolProductUse;
import com.homedo.odin.solution.model.entity.Solution;
import com.homedo.odin.solution.model.entity.UserBasic;
import com.homedo.odin.solution.service.SolProductListServiceImpl;
import com.homedo.odin.solution.service.SolProductUseServiceImpl;
import com.homedo.odin.solution.service.UserBasicServiceImpl;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeSet;
import javax.servlet.http.HttpServletResponse;
import net.sf.json.JSONArray;
import net.sf.json.JsonConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
public class ExportProductListBizService {

    @Autowired
    SolProductUseServiceImpl solProductUseService;

    @Autowired
    SolProductListServiceImpl solProductListService;

    @Autowired
    UserBasicServiceImpl userBasicService;

    @Autowired
    MessageBizService messageBizService;

    @Autowired
    SolutionMapper solutionMapper;

    @Transactional(rollbackFor = {RuntimeException.class, Exception.class})
    public ExportExcelResp exportSolution(ExportExcelReq req) throws Exception {
        ExportExcelResp resp = new ExportExcelResp();
        //数据校验
        if (req.getUserId() <= 0 || req.getListId() <= 0 || req.getSolProductDetailBeanList() == null) {
            throw new BizException(Meta.CODE_451.getCode(), "请求参数非法");
        }

        if (req.getSolProductDetailBeanList() == null || req.getSolProductDetailBeanList().size() == 0) {
            throw new BizException(Meta.CODE_451.getCode(), "请求参数非法");
        }
        //第一步：将数据插入到sol_product_use表
        UserBasic userBasic = userBasicService.selectByUserId(req.getUserId());
        if (userBasic == null) {
            throw new BizException(Meta.CODE_451.getCode(), "不存在该用户");
        }
        List<SolProductDetailBean> list = convertList(req.getSolProductDetailBeanList());
        String content = JsonUtils.toJSONString(list);
        SolProductUse solProductUse = new SolProductUse();
        solProductUse.setCreatedBy(req.getUserId());
        solProductUse.setModifiedBy(req.getUserId());
        solProductUse.setListId(req.getListId());
        solProductUse.setUserName(userBasic.getUserName());
        solProductUse.setContent(content);
        int result1 = solProductUseService.insertDoadloadJson(solProductUse);
        if (result1 <= 0) {
            throw new BizException(Meta.CODE_500.getCode(), "将数据插入到sol_product_use表失败");
        }
        //第二步：更新sol_product_list表中download_count（下载数量）
        SolProductList solProductList = solProductListService.getProductListById(req.getListId());
        if (solProductList == null) {
            throw new BizException(Meta.CODE_500.getCode(), "不存在该产品清单");
        }
        int oldCount = solProductList.getDownloadCount();
        solProductList.setDownloadCount(oldCount + 1);
        boolean result2 = solProductListService.updateById(solProductList);
        if (!result2) {
            throw new BizException(Meta.CODE_500.getCode(), "更新sol_product_list表中download_count（下载数量）失败");
        }
        resp.setId(solProductUse.getId());
        return resp;

    }

    /**
     * 导出excel
     */
    public void export(int id, HttpServletResponse response) throws Exception {
        //1.根据id获取下载内容json
        Map<String, Object> map = new HashMap<>();
        map.put("id", id);
        map.put("is_del", 0);
        List<SolProductUse> list = solProductUseService.selectByMap(map);
        if (list == null || list.size() == 0) {
            throw new BizException(Meta.CODE_500.getCode(), "不存在方案产品清单下载使用数据");
        }
        SolProductUse solProductUse = list.get(0);
        JSONArray jsonArray1 = JSONArray.fromObject(solProductUse.getContent());
        List<SolProductDetailBean> solProductDetailBeanList = JSONArray
                .toList(jsonArray1, new SolProductDetailBean(), new JsonConfig());
        //2.开始导出
        List<List<Object>> rows = new ArrayList();
        for (SolProductDetailBean ve : solProductDetailBeanList
                ) {
            List<Object> row = new ArrayList();
            row.add(ve.getSysSort());
            row.add(ve.getSysType());
            row.add(ve.getProductName());
            row.add(ve.getModel());
            row.add(ve.getBrand());
            row.add(ve.getAmount());
            row.add(ve.getUnit());
            row.add(ve.getPrice());
            rows.add(row);
        }
        List<String> titles = new ArrayList<>();
        titles.add("系统");
        titles.add("二级系统");
        titles.add("产品名称");
        titles.add("产品型号");
        titles.add("品牌");
        titles.add("数量");
        titles.add("单位");
        titles.add("参考价");

        ExcelData data = new ExcelData();
        data.setTitles(titles);
        data.setRows(rows);
        exportExcel("产品配置清单.xlsx", data, response);

    }

    private void exportExcel(String title, ExcelData data, HttpServletResponse response) throws Exception {
        ExportExcelUtils.exportExcel(response, title, data);
    }


    private List<SolProductDetailBean> convertList(List<Tree> trees) {

        if (trees != null && trees.size() > 0) {
            List<SolProductDetailBean> solProductDetails = new ArrayList<>();
            for (Tree tr : trees
                    ) {
                //SolProductDetailBean solProductDetail = new SolProductDetailBean();

                if (tr.getChild() != null && tr.getChild().size() > 0) {
                    for (Tree tr1 : tr.getChild()
                            ) {
                        for (Tree tr3 : tr1.getChild()
                                ) {
                            SolProductDetailBean solProductDetail = new SolProductDetailBean();
                            solProductDetail.setSysSort(tr.getLevelName());
                            solProductDetail.setSysType(tr1.getLevelName());
                            solProductDetail.setAmount(tr3.getAmount());
                            solProductDetail.setBrand(tr3.getBrand());
                            solProductDetail.setListId(tr3.getListId());
                            solProductDetail.setModel(tr3.getModel());
                            solProductDetail.setPrice(tr3.getPrice());
                            solProductDetail.setProductName(tr3.getProductName());
                            solProductDetail.setSkuId(tr3.getSkuId());
                            solProductDetail.setUnit(tr3.getUnit());
                            solProductDetails.add(solProductDetail);
                        }
                    }


                }

            }
            return solProductDetails;
        }

        return null;

    }

    /**
     * 关联的方案
     * 查找相关方案  相关方案先找该用户的方案 没有找该方案相同系统分类的方案、还没有就找相关业态分类的方案
     * @return
     */
  public List<RelatedSolutionResponseBean> queryRelatedSolution(Solution solution, Long solutionId,Integer num) {
      List<RelatedSolutionResponseBean> relatedSolutionResponseBeans = new ArrayList<RelatedSolutionResponseBean>();
      Integer firstSysTag = solution.getFirstSysAttr();

      //相关方案先找该用户的方案
      List<Solution>  queryInfoUser = solutionMapper.queryRelatedUserSolution(solution.getUserId(),solutionId,solution.getSolutionType(),num);

      //相同系统分类
      List<Solution>  querySystemFirst =  solutionMapper.queryRelatedFirstSystemSolution(firstSysTag,solutionId,solution.getSolutionType(),num);

       //查相关业态分类
      String  buildType = solution.getBuildingType();
      List<Solution> queryListBuildType = new ArrayList<>();
      if(buildType!=null&&!buildType.equals("")){
          //如果有多个业态，则取第一个业态
          String[] buildTypes = buildType.split(",");
          if(buildTypes.length>0){
              String chooseBuildTypes = buildTypes[0];
              queryListBuildType =   solutionMapper.queryRelatedBuildingTypeSolution(buildType,solutionId,solution.getSolutionType(),num);
          }
      }

      List<Solution> resp = new ArrayList<Solution>();
      //去重
      for(Solution solutionUser:queryInfoUser){
          if(!resp.contains(solutionUser)){
              resp.add(solutionUser);
          }
      }
      for (Solution solutionSystemFirst:querySystemFirst){
          if(!resp.contains(solutionSystemFirst)) {
              resp.add(solutionSystemFirst);
          }
      }
      for (Solution solutionBuildType:queryListBuildType){
          if(!resp.contains(solutionBuildType)) {
              resp.add(solutionBuildType);
          }
      }

      /*resp = resp.stream().collect(
          collectingAndThen( toCollection(() -> new TreeSet<>(comparingLong(Solution::getId))), ArrayList::new)
      );*/

      //大于5条只取5条
      if(resp.size()>num){
          resp = resp.subList(0,num);
      }
      relatedSolutionResponseBeans = BeanUtils.batchTransform(RelatedSolutionResponseBean.class,resp);
      return relatedSolutionResponseBeans;
   }

}
